import React, {useEffect, useState} from "react";
import {Button, Input, Pagination, Popconfirm, Space, Table, Tooltip, Modal, Upload, Spin, notification, Radio, DatePicker, Select, Tag} from "antd";

import Header from "../components/Header";
import Footer from "../components/Footer";

import http from "../request";
import {BASE_URL, UPLOAD_URL} from "../request/api";
import {fieldGet, paramChange} from "../common/common";
import {PlusOutlined} from "@ant-design/icons";
import {store} from "../store";
import moment from "moment";
import Recycle from "../components/Recycle";
import ResizeableTitle from "../components/ResizableTitle";

const { Option } = Select;

const Store = () => {
    const pageDefault = {page: 1, pageSize: 10}
    const [storeSearch, setStoreSearch] = useState({})
    const [storeSource, setStoreSource] = useState([])
    const [storeColumn, setstoreColumn] = useState([
        {
            title: '封面',
            dataIndex: 'image',
            width: 60,
            render: e => e ? <img className="avatar" src={BASE_URL + e} alt=""/> : ''
        }, {
            title: '名称',
            width:250,
            dataIndex: 'name'
        }, {
            title: '地址',
            width:300,
            dataIndex: 'address',
            render: e => (
                <Tooltip title={e}>
                    <div className="u-line-1" style={{maxWidth: 300}}>{e}</div>
                </Tooltip>
            )
        }, {
            title: '备注',
            dataIndex: 'memo',
            width:300,
            render: e => (
                <Tooltip title={e}>
                    <div className="u-line-1" style={{maxWidth: 300}}>{e}</div>
                </Tooltip>
            )
        }, {
            title: '操作',
            render: e => (
                <Space size="middle">
                    <img className="u-btn" src={require('../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => storeEdit(e.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() => storeDel(e.id)}>
                        <img className="u-btn" src={require('../assets/icon/icon-13.png').default} alt="" title="删除"/>
                    </Popconfirm>
                </Space>
            )
        }
    ])
    const [storePager, setStorePager] = useState(pageDefault)
    const [storeTotal, setStoreTotal] = useState(0)
    const [storeSelect, setStoreSelect] = useState([])
    const [storeShow, setStoreShow] = useState(!1)
    const [storeForm, setStoreForm] = useState({})
    const [storeImg, setStoreImg] = useState([])

    const [staffSearch, setStaffSearch] = useState({})
    const [staffSource, setStaffSource] = useState([])
    const [staffColumn, setstaffColumn] = useState([
        {
            title: '头像',
            dataIndex: 'avatar',
            width: 60,
            render: e => e ? <img className="avatar" src={e} alt=""/> : ''
        }, {
            title: '名称',
            width:250,
            dataIndex: 'nickname'
        }, {
            title: '性别',
            dataIndex: 'gender',
            width:250,
            render: e => (
                <Space size="middle">
                    {e === 1 && <Tag color="blue">男</Tag>}
                    {e === 2 && <Tag color="red">女</Tag>}
                </Space>
            )
        }, {
            title: '生日',
            width:250,
            dataIndex: 'birthday'
        }, {
            title: '管理员身份',
            width:250,
            dataIndex: 'group',
            render: e => e?.name ?? ''
        }, {
            title: '操作',
            render: e => (
                <Space size="middle">
                    <img className="u-btn" src={require('../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => staffEdit(e.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() => staffDel(e.id)}>
                        <img className="u-btn" src={require('../assets/icon/icon-13.png').default} alt=""  title="删除"/>
                    </Popconfirm>
                </Space>
            )
        }
    ])
    const [staffPager, setStaffPager] = useState(pageDefault)
    const [staffTotal, setStaffTotal] = useState(0)
    const [staffSelect, setStaffSelect] = useState([])
    const [staffShow, setStaffShow] = useState(!1)
    const [staffForm, setStaffForm] = useState({})
    const [staffImg, setStaffImg] = useState([])

    const [preview, setPreview] = useState({show: !1, content: ''})

    const [mask, setMask] = useState({show: !1, text: ''})

    const [haveStore, setHaveStore] = useState(!1)
    const [allStore, setAllStore] = useState([])
    const [allAuth, setAllAuth] = useState([])

    const uploadConfig = {
        name: "file",
        accept: 'image/*',
        listType: 'picture-card',
        action: UPLOAD_URL,
        headers: {
            token: store.getState().userInfo.token
        },
        onPreview: (file) => {
            setPreview({
                show: !0,
                content: BASE_URL + file.response.data.url
            })
        }
    }

    // 回收站-列
    const storeBackColumns = [
        {
            title: '封面',
            dataIndex: 'image',
            width: 60,
            render: e => e ? <img className="avatar" src={BASE_URL + e} alt=""/> : ''
        }, {
            title: '名称',
            dataIndex: 'name'
        }, {
            title: '地址',
            dataIndex: 'address',
            render: e => (
                <Tooltip title={e}>
                    <div className="u-line-1" style={{maxWidth: 300}}>{e}</div>
                </Tooltip>
            )
        }, {
            title: '备注',
            dataIndex: 'memo',
            render: e => (
                <Tooltip title={e}>
                    <div className="u-line-1" style={{maxWidth: 300}}>{e}</div>
                </Tooltip>
            )
        }
    ]
    const staffBackColumns = [
        {
            title: '头像',
            dataIndex: 'avatar',
            width: 60,
            render: e => e ? <img className="avatar" src={e} alt=""/> : ''
        }, {
            title: '名称',
            dataIndex: 'nickname'
        }, {
            title: '性别',
            dataIndex: 'gender',
            render: e => (
                <Space size="middle">
                    {e === 1 && <Tag color="blue">男</Tag>}
                    {e === 2 && <Tag color="red">女</Tag>}
                </Space>
            )
        }, {
            title: '生日',
            dataIndex: 'birthday'
        }, {
            title: '管理员身份',
            dataIndex: 'group',
            render: e => e?.name ?? ''
        }
    ]

    const [change, setchange] = useState(!0)
    const [chang, setchang] = useState(!0)

    useEffect(() => {
        storeGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [storePager])
    useEffect(() => {
        staffGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [staffPager])
    useEffect(() => {
        !storeShow && storeReset()
    }, [storeShow])
    useEffect(() => {
        if(staffShow && !haveStore){
            getAllStore()
            getAllAuth()
        }
        !staffShow && staffReset()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [staffShow])

    return (
        <React.Fragment>
            <Header navCur={6}/>
            <div className="Store page u-m-20 u-p-20">
                <div className="part-title">部门管理</div>
                <div className="u-flex u-row-between u-m-t-20">
                    <Recycle url='store' change={setchang} func={storeGet} columns={storeBackColumns} className="u-m-r-20" />
                    <div className="u-flex">
                        <Input value={storeSearch.name} onChange={e => paramChange(setStoreSearch, storeSearch, 'name', e.target.value)} placeholder="部门名称" style={{width: 200}} />
                        <Button size="mini" type="primary" onClick={storeFind}>
                            <img src={require('../assets/icon/icon-6.png').default} alt="" />
                        </Button>
                    </div>
                </div>
                <div className="u-m-t-20">
                    <Table bordered size="small" rowSelection={{
                        selectedRowKeys: storeSelect,
                        onChange(e){
                            setStoreSelect(e)
                        }
                    }} onRow={e => ({
                        onDoubleClick: () => {
                            storeEdit(e.id)
                        }
                    })} rowKey={e => e.id} components={{
                        header: {
                            cell: ResizeableTitle
                        }
                    }} dataSource={storeSource} columns={storeColumn.map((col, index) => {
                        return {
                            ...col,
                            onHeaderCell: (column) => ({
                                width: column.width,
                                onResize: (e, { size }) => {
                                    setstoreColumn((storeColumn) => {
                                        const nextColumns = [...storeColumn];
                                        nextColumns[index] = {
                                            ...nextColumns[index],
                                            width: size.width
                                        }
                                        return nextColumns;
                                    })
                                }
                            })
                        }
                    })} pagination={false} />
                </div>
                <div className="u-flex u-row-between u-m-t-20">
                    <div>
                        <Button type="primary" size="small" onClick={() => setStoreShow(!0)}>
                            <div className="u-flex">
                                <img src={require('../assets/icon/icon-18.png').default} alt=""/>
                                <span className="u-m-l-5">新增</span>
                            </div>
                        </Button>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={storeDel}>
                            <Button className="u-m-l-20" type="primary" size="small" danger>
                                <div className="u-flex">
                                    <img src={require('../assets/icon/icon-19.png').default} alt=""/>
                                    <span className="u-m-l-5">删除</span>
                                </div>
                            </Button>
                        </Popconfirm>
                    </div>
                    <Pagination showQuickJumper current={storePager.page} pageSize={storePager.pageSize} total={storeTotal} />
                </div>
            </div>
            <Modal visible={storeShow} width={300} title="部门" onOk={storeConfirm} onCancel={() => setStoreShow(!1)}>
                <div className="Modal">
                    { mask.show && <div className="mask">
                        <Spin size="large" tip={mask.text} />
                    </div> }
                    <div className="u-flex">
                        <div className="label u-text-nowrap">封面</div>
                        <Upload {...uploadConfig} fileList={storeImg} onChange={({fileList}) => {
                            let newForm = {...storeForm}
                            newForm.image = fileList[0]?.response?.data?.url ?? ''
                            setStoreForm(newForm)
                            setStoreImg(fileList)
                        }} className="u-m-l-10">
                            { storeImg.length < 1 && ( <div>
                                <PlusOutlined />
                                <div style={{ marginTop: 8 }}>Upload</div>
                            </div>) }
                        </Upload>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">名称</div>
                        <Input value={storeForm.name} onChange={e => paramChange(setStoreForm, storeForm, 'name', e.target.value)} placeholder="部门名称" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">地址</div>
                        <Input value={storeForm.address} onChange={e => paramChange(setStoreForm, storeForm, 'address', e.target.value)} placeholder="部门地址" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">描述</div>
                        <Input value={storeForm.memo} onChange={e => paramChange(setStoreForm, storeForm, 'memo', e.target.value)} placeholder="描述" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                </div>
            </Modal>

            <div className="Store page u-m-20 u-p-20">
                <div className="part-title">员工管理</div>
                <div className="u-flex u-row-between u-m-t-20">
                    <Recycle url='user'change={setchange} func={staffGet} columns={staffBackColumns} className="u-m-r-20" />
                    <div className="u-flex">
                        <Input value={staffSearch.name} onChange={e => paramChange(setStaffSearch, staffSearch, 'nickname', e.target.value)} placeholder="员工名称" style={{width: 200}} />
                        <Button size="mini" type="primary" onClick={staffFind}>
                            <img src={require('../assets/icon/icon-6.png').default} alt="" />
                        </Button>
                    </div>
                </div>
                <div className="u-m-t-20">
                    <Table bordered size="small" rowSelection={{
                        selectedRowKeys: staffSelect,
                        onChange(e){
                            setStaffSelect(e)
                        }
                    }} onRow={e => ({
                        onDoubleClick: () => {
                            staffEdit(e.id)
                        }
                    })} rowKey={e => e.id} components={{
                        header: {
                            cell: ResizeableTitle
                        }
                    }} dataSource={staffSource} columns={staffColumn.map((col, index) => {
                        return {
                            ...col,
                            onHeaderCell: (column) => ({
                                width: column.width,
                                onResize: (e, { size }) => {
                                    setstaffColumn((staffColumn) => {
                                        const nextColumns = [...staffColumn];
                                        nextColumns[index] = {
                                            ...nextColumns[index],
                                            width: size.width
                                        }
                                        return nextColumns;
                                    })
                                }
                            })
                        }
                    })} pagination={false} />
                </div>
                <div className="u-flex u-row-between u-m-t-20">
                    <div>
                        <Button type="primary" size="small" onClick={() => setStaffShow(!0)}>
                            <div className="u-flex">
                                <img src={require('../assets/icon/icon-18.png').default} alt=""/>
                                <span className="u-m-l-5">新增</span>
                            </div>
                        </Button>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={staffDel}>
                            <Button className="u-m-l-20" type="primary" size="small" danger>
                                <div className="u-flex">
                                    <img src={require('../assets/icon/icon-19.png').default} alt=""/>
                                    <span className="u-m-l-5">删除</span>
                                </div>
                            </Button>
                        </Popconfirm>
                    </div>
                    <Pagination showQuickJumper current={staffPager.page} pageSize={staffPager.pageSize} total={staffTotal} />
                </div>
            </div>
            <Modal visible={staffShow} width={300} title="员工" onOk={staffConfirm} onCancel={() => setStaffShow(!1)}>
                <div className="Modal">
                    { mask.show && <div className="mask">
                        <Spin size="large" tip={mask.text} />
                    </div> }
                    <div className="u-flex">
                        <div className="label">部门</div>
                        <Select value={staffForm.store_id} onChange={e => paramChange(setStaffForm, staffForm, 'store_id', e)} placeholder="部门" className="u-m-l-10" style={{width: 200}}>
                            { allStore.map(store => (
                                <Option key={'store-'+store.id} value={store.id}>{store.name}</Option>
                            )) }
                        </Select>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">身份</div>
                        <Select value={staffForm.group_id} onChange={e => paramChange(setStaffForm, staffForm, 'group_id', e)} placeholder="管理员身份" className="u-m-l-10" style={{width: 200}}>
                            { allAuth.map(group => (
                                
                                <Option key={'store-'+group.id} value={group.id}>{group.name}</Option>
                            )) }
                        </Select>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label u-text-nowrap">头像</div>
                        <Upload {...uploadConfig} fileList={staffImg} onChange={({fileList}) => {
                            let newForm = {...staffForm}
                            newForm.avatar = fileList[0]?.response?.data?.url ? BASE_URL + fileList[0].response.data.url : ''
                            setStaffForm(newForm)
                            setStaffImg(fileList)
                        }} className="u-m-l-10">
                            { staffImg.length < 1 && ( <div>
                                <PlusOutlined />
                                <div style={{ marginTop: 8 }}>Upload</div>
                            </div>) }
                        </Upload>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">名称</div>
                        <Input value={staffForm.nickname} onChange={e => paramChange(setStaffForm, staffForm, 'nickname', e.target.value)} placeholder="员工名称" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">密码</div>
                        <Input.Password value={staffForm.password} onChange={e => paramChange(setStaffForm, staffForm, 'password', e.target.value)} placeholder="密码，不修改请留空" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">性别</div>
                        <Radio.Group onChange={e => paramChange(setStaffForm, staffForm, 'gender', e.target.value)} value={staffForm.gender} className="u-m-l-10">
                            <Radio value={1}>男</Radio>
                            <Radio value={2}>女</Radio>
                        </Radio.Group>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">生日</div>
                        <DatePicker value={staffForm.birthday?moment(staffForm.birthday):''} onChange={(e, es) => paramChange(setStaffForm, staffForm, 'birthday', es)} placeholder="生日" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                </div>
            </Modal>

            <Modal visible={preview.show} width={1000} footer={null} zIndex={1010} onCancel={() => {setPreview({show: !1})}}>
                <img src={preview.content} alt="" style={{width: '100%'}}/>
            </Modal>
            <Footer/>
        </React.Fragment>
    )
    function storeGet(){
        if(chang && JSON.parse(sessionStorage.getItem('store_list'))){
            const house = JSON.parse(sessionStorage.getItem('store_list'))
            for (const key in house.rows) {
                if (key*1 === storePager.page) {
                    setStoreSource(house.rows[key])
                    setStoreTotal(house.total)
                    return
                }
            }
        }
        http('store.list', {
            ...fieldGet(
                {name: 'like'},
                storeSearch,
                storePager.page,
                storePager.pageSize
            )
        }).then(res => {
            if(res.code === 1){
                const page = storePager.page
                    if(storeTotal && chang){
                        let arr = JSON.parse(sessionStorage.getItem('store_list'))
                        arr.rows[page] = []
                        res.data.rows.forEach(i=>arr.rows[page].push(i))
                        sessionStorage.setItem('store_list',JSON.stringify(arr))
                        setchang(!0)
                        setStoreSource(res.data.rows)
                        setStoreTotal(res.data.total)
                        return
                    }
                    const data = {
                        total:res.data.total,
                        rows:{
                            [page]:res.data.rows
                        }
                    }
                    sessionStorage.setItem('store_list',JSON.stringify(data))
                    setchang(!0)
                setStoreSource(res.data.rows)
                setStoreTotal(res.data.total)
            }
        })
    }
    function storeFind(){
        setchang(!1)
        let pager = {...storePager}
        pager.size = 1
        setStorePager(pager)
    }
    function storeReset(){
        setchang(!1)
        setStoreForm({})
        setStoreImg([])
        setMask({show: !1, text: ''})
    }
    function storeConfirm(){
        setMask({show: !0, text: '提交中...'})
        let newForm = {...storeForm}
        let url = newForm?.id ? 'store.edit' : 'store.add'
        http(url, {
            row: newForm
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '添加成功'
                })
                setchang(!1)
                setStoreShow(!1)
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            storeGet()
            setMask({show: !1, text: ''})
        })
    }
    function storeEdit(ids){
        http('store.one', {ids}).then(res => {
            if(res.code === 1){
                setStoreForm(res.data)
                setStoreImg([{url: BASE_URL + res.data.image}])
                setStoreShow(!0)
            }
        })
    }
    function storeDel(id){
        let ids = id > 0 ? [id] : storeSelect
        http('store.del', {ids}).then(res => {
            if(res.code === 1){
                setchang(!1)
                storeGet()
            }
        })
    }

    function staffGet(){
        if(change && JSON.parse(sessionStorage.getItem('staff_list'))){
            const house = JSON.parse(sessionStorage.getItem('staff_list'))
            for (const key in house.rows) {
                if (key*1 === staffPager.page) {
                    setStaffSource(house.rows[key])
                    setStaffTotal(house.total)
                    return
                }
            }
        }
        http('user.index', {
            ...fieldGet(
                {name: 'like'},
                staffSearch,
                staffPager.page,
                staffPager.pageSize
            )
        }).then(res => {
            if(res.code === 1){
                    const page = staffPager.page
                    if(staffTotal && change){
                        let arr = JSON.parse(sessionStorage.getItem('staff_list'))
                        arr.rows[page] = []
                        res.data.rows.forEach(i=>arr.rows[page].push(i))
                        sessionStorage.setItem('staff_list',JSON.stringify(arr))
                        setchange(!0)
                        setStaffSource(res.data.rows)
                        setStaffTotal(res.data.total)
                        return
                    }
                    const data = {
                        total:res.data.total,
                        rows:{
                            [page]:res.data.rows
                        }
                    }
                    sessionStorage.setItem('staff_list',JSON.stringify(data))
                    setchange(!0)
                setStaffSource(res.data.rows)
                setStaffTotal(res.data.total)
            }
        }).catch(err=>console.log(err))
    }
    function staffFind(){
        setchange(!1)
        let pager = {...staffPager}
        pager.size = 1
        setStaffPager(pager)
    }
    function staffReset(){
        setchange(!1)
        setStaffForm({})
        setStaffImg([])
        setMask({show: !1, text: ''})
    }
    function staffConfirm(){
        setMask({show: !0, text: '提交中...'})
        let newForm = {...staffForm}
        newForm.username = newForm.nickname
        newForm.user_id = store.getState().userInfo.id
        let url = newForm?.id ? 'user.edit' : 'user.add'
        console.log(newForm);
        http(url, {
            row: newForm
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '添加成功'
                })
                setchange(!1)
                setStaffShow(!1)
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            staffGet()
            setMask({show: !1, text: ''})
        })
    }
    function staffEdit(ids){
        http('user.one', {ids}).then(res => {
            if(res.code === 1){
                let user = res.data
                setStaffForm({
                    id: user.id,
                    avatar: user.avatar,
                    nickname: user.nickname,
                    gender: user.gender,
                    birthday: user.birthday,
                    store_id: user.store_id,
                    group_id: user.group_id,
                    password: ''
                })
                setStaffImg([{url: user.avatar}])
                setStaffShow(!0)
            }
        })
    }
    function staffDel(id){
        let ids = id > 0 ? [id] : staffSelect
        http('user.del', {ids}).then(res => {
            if(res.code === 1){
                setchange(!1)
                staffGet()
            }
        })
    }

    function getAllStore(){
        http('store.list').then(res => {
            if(res.code === 1){
                setHaveStore(!0)
                setAllStore(res.data.rows)
            }
        })
    }

    // 请求身份信息
    function getAllAuth(){
        http('auth.list').then(res => {
            console.log(res);
            if(res.code === 1){
                setAllAuth(res.data.rows)
            }
        })
    }
}

export default Store;